package com.killer.controller;

import com.killer.pojo.AuthCode;
import com.killer.service.CodeService;
import com.killer.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ：Killer
 * @date ：Created in 20-12-31 下午3:16
 * @description：${description}
 * @modified By：
 * @version: version
 */
@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private CodeService codeService;

    @RequestMapping("/create/{email}")
    public Boolean generateCode(@PathVariable String email){
        try {
            codeService.generateCode(email);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @RequestMapping("/validate/{email}/{code}")
    public Integer validateCode(@PathVariable String email, @PathVariable String code) {
        AuthCode authCode = codeService.getLastAuthCodeByEmail(email);
        //判断
        if(authCode == null){
            //代表没发送过，即错误
            return 1;
        }
        if (StringUtils.equals(code, authCode.getCode())) {
            //判断是否超时
            if (DateUtil.getNow().getTime() > authCode.getExpiretime().getTime()) {
                return 2;
            }else{
                return 0;
            }
        }else{
            //验证码不对应，则是错误
            return 1;
        }
    }
}
